package com.warrantyhotel.android.ui;

import java.util.Timer;
import java.util.TimerTask;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.warrantyhotel.android.R;
import com.warrantyhotel.android.model.Keys;
import com.warrantyhotel.android.service.UpdateIntentService;
import com.warrantyhotel.android.util.DetachableResultReceiver;
import com.warrantyhotel.android.util.DetachableResultReceiver.Receiver;
import com.warrantyhotel.android.util.ToastUtil;
import com.warrantyhotel.android.util.imLoader2.ImageLoader;

public class WarrantyApplication extends Application implements Receiver {

	public Typeface typefaceHelvetica;
	private ImageLoader mImageLoader;
	private ImageLoader imageLoader;
	private Timer timer;
	private DetachableResultReceiver receiver;

	@Override
	public void onCreate() {
		super.onCreate();
		mImageLoader = new ImageLoader(getApplicationContext());
		imageLoader = new ImageLoader(getApplicationContext());
		typefaceHelvetica = Typeface.createFromAsset(getAssets(), "fonts/helvetica.ttf");

		receiver = new DetachableResultReceiver(new Handler());
		receiver.setReceiver(this);

		// IntentFilter intentFilter = new
		// IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION);
		// registerReceiver(receiverConnection, intentFilter);

	}

	// BroadcastReceiver receiverConnection = new BroadcastReceiver() {
	//
	// @Override
	// public void onReceive(Context context, Intent intent) {
	// Bundle extras = intent.getExtras();
	// if (extras != null) {
	// boolean isInetEnable =
	// extras.getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY);
	// if (isInetEnable) {
	// ToastUtil.showText(getApplicationContext(),
	// getString(R.string.conn_avaliable));
	// }
	// }
	//
	// }
	// };

	public DetachableResultReceiver getReceiver() {
		return receiver;
	}

	public ImageLoader getImageLoader() {
		return mImageLoader;
	}

	public ImageLoader getImageLoaderNew() {
		return imageLoader;
	}

	public boolean isInternetPresent() {
		ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = manager.getActiveNetworkInfo();
		boolean isInternet;

		isInternet = (info == null || !info.isConnected() || info.isRoaming()) ? false : true;

		return isInternet;
	}

	public Typeface getTypefaceHelvetica() {
		return typefaceHelvetica;
	}

	class UpdateTimeTask extends TimerTask {
		public void run() {
			if (isMyServiceRunning()) {
				handler.sendEmptyMessage(1);

			}
		}
	}

	private boolean isMyServiceRunning() {
		ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		for (RunningTaskInfo activity : manager.getRunningTasks(Integer.MAX_VALUE)) {
			if ("com.warrantyhotel.android".equals(activity.baseActivity.getPackageName())) {
				return true;
			}
		}
		return false;
	}

	public void startExpireSession(long time) {
		timer = new Timer();
		timer.schedule(new UpdateTimeTask(), time);
	}

	public Timer getTimer() {
		return timer;
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				ToastUtil.showText(getApplicationContext(), getString(R.string.session_expired));
				if (isMyServiceRunning())
					android.os.Process.killProcess(android.os.Process.myPid());
				break;
			default:
				break;
			}

		}

	};

	@Override
	public void onReceiveResult(int resultCode, Bundle resultData) {
		switch (resultCode) {
		case UpdateIntentService.STATUS_RUNNING:
			break;
		case UpdateIntentService.STATUS_ERROR:
			break;
		case UpdateIntentService.STATUS_FINISHED:
			if (resultData.containsKey(Keys.isPurchaced)) {
				boolean isPurchased = resultData.getBoolean(Keys.isPurchaced);
				showNotification(isPurchased);
			}

			break;
		default:
			break;
		}

	}

	protected void showNotification(boolean result) {
		// look up the notification manager service
		NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		// The details of our fake message
		CharSequence from = getString(R.string.imcoming_message_ticker_text);
		CharSequence message = (result) ? getString(R.string.purchase_message_positive) : getString(R.string.purchase_message_negative);

		// The PendingIntent to launch our activity if the user selects this
		// notification

		// Intent intent = new Intent(this, SplashScreenActivity.class);
		// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);

		// The ticker text, this uses a formatted string so our message could be
		// localized
		String tickerText = getString(R.string.imcoming_message_ticker_text, message);

		// construct the Notification object.
		Notification notif = new Notification(R.drawable.icon_warranty, tickerText, System.currentTimeMillis());

		// Set the info for the views that show in the notification panel.
		notif.setLatestEventInfo(this, from, message, contentIntent);

		/*
		 * // On tablets, the ticker shows the sender, the first line of the
		 * message, // the photo of the person and the app icon. For our sample,
		 * we just show // the same icon twice. If there is no sender, just pass
		 * an array of 1 Bitmap. notif.tickerTitle = from; notif.tickerSubtitle
		 * = message; notif.tickerIcons = new Bitmap[2]; notif.tickerIcons[0] =
		 * getIconBitmap();; notif.tickerIcons[1] = getIconBitmap();;
		 */

		// after a 0ms delay, vibrate for 250ms, pause for 100 ms and
		// then vibrate for 500ms.
		notif.vibrate = new long[] { 0, 250, 100, 500 };

		// Note that we use R.layout.incoming_message_panel as the ID for
		// the notification. It could be any integer you want, but we use
		// the convention of using a resource id for a string related to
		// the notification. It will always be a unique number within your
		// application.
		nm.notify(R.string.imcoming_message_ticker_text, notif);
	}

}
